/*
ajax请求函数模块
返回值: promise对象(异步返回的数据是: response.data)
 */
import axios from 'axios';
import router from "../router";
import store from '../store';
import common from '../common/common';

export default function ajax(url, data = {}, type = 'GET') {
    return new Promise(function (resolve, reject) {
        // 执行异步ajax请求
        let promise;
        // 准备url query参数数据
        let dataStr = ''; //数据拼接字符串
        data = data || {};
        Object.keys(data).forEach(key => {
            dataStr += key + '=' + data[key] + '&';
        })
        if (dataStr !== '') {
            dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'));
        }
        if (type === 'GET') {
            if (dataStr !== '') {
                url = url + '?' + dataStr;
            }
            // 发送get请求
            promise = axios.get(url);
        } else {
            // 发送post请求
            promise = axios.post(url, dataStr);
        }
        promise.then(function (response) {
            // 成功了调用resolve()
            resolve(response.data);
        }).catch(function (error) {
            //失败了调用reject()
            reject(error);
        })
    });
}

//请求发送拦截，把数据发送给后台之前做些什么......
axios.interceptors.request.use((request) => {
    //请求头添加token
    let token = localStorage.getItem('token') || '';
    if (token) {
        request.headers['token'] = token;
    }
    request.headers['x-requested-with'] = 'XMLHttpRequest';
    request.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    //再发送给后台
    return request;
}, (error) => {
    return Promise.reject(error)
});

//请求返回拦截，把数据返回到页面之前做些什么...
axios.interceptors.response.use((response) => {
    //code为2时，需要登录
    //code为3时，需要刷新
    console.log(response);
    if (response.data.code === '3') {
        //刷新token
        let {token} = response.data;
        localStorage.setItem("token", token);
        //重新发起请求
        var backoff = new Promise(function (resolve) {
            setTimeout(function () {
                resolve();
            }, 1000);
        });
        // 重新发送请求
        return backoff.then(function () {
            return axios(response.config);
        });
    }
    if (response.data.code == '2') {
        common.toast('fail', 'token失效，需重新登录！', () => {
            store.dispatch('logout');
            router.push("/login");
        });
    }
    return response;
}, (error) => {
    return Promise.reject(error)
});
